package com.lbyl.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lbyl.activitiy.R;
import com.lbyl.adapter.topnews.TopNewsViewPagerAdapter;
import com.lbyl.fragment.pager.TopNewsFragmentPager;
import com.lbyl.pref.Pref;
import com.viewpagerindicator.TabPageIndicator;

import java.util.ArrayList;

/**
 * @author libin996@outlook.com
 */

public class TopNewsFragment extends Fragment {
    private static final String TAG = "TopNewsFragment";

    private ViewPager viewpager_topnews;
    private View view_fragment_topnews;
    private ArrayList<String> topNewsPagerTitleList;
    private ArrayList<TopNewsFragmentPager> fragmentList;


    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //初始化fragment的view
        view_fragment_topnews = inflater.inflate(R.layout.fragment_topnews, container, false);

        //初始化viewpager
        initViewPager();

        //初始化viewpagerIndicator
        initIndicator();

        return view_fragment_topnews;

    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        Log.d(TAG, "initViewPager() 调用");

        viewpager_topnews = (ViewPager) view_fragment_topnews.findViewById(R.id.viewpager_topnews);
        topNewsPagerTitleList = Pref.getPagerTitleList();
        initFragmentList();

        Log.i(TAG, "initViewPager:即将设置adapter");
        TopNewsViewPagerAdapter adapter = new TopNewsViewPagerAdapter(getChildFragmentManager(), fragmentList);
        viewpager_topnews.setAdapter(adapter);
    }

    /**
     * 初始化每个fragment.根据title维护到list中,设置tag
     */
    private void initFragmentList() {
        Log.i(TAG, "initFragmentList: 开始初始化manager");
        fragmentList = new ArrayList<>();
        for (int i = 0; i < topNewsPagerTitleList.size(); i++) {
            TopNewsFragmentPager pager = new TopNewsFragmentPager();
            pager.setTitle(topNewsPagerTitleList.get(i));
            fragmentList.add(pager);
        }

    }

    /**
     * 初始化初始化viewpagerIndicator
     */
    private void initIndicator() {
        TabPageIndicator indicator_topnews = (TabPageIndicator) view_fragment_topnews.findViewById(R.id.indicator_topnews);
        indicator_topnews.setViewPager(viewpager_topnews);
        indicator_topnews.setVisibility(View.VISIBLE);
    }


}
